package Log

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"time"
)

type HarkLog struct {
	Timestamp       time.Time
	RequestIp      string
	Method          string
	Name            string
	User            string
	AccessTokenHash string
	RawQuery        string
	Attributes      map[string]interface{}
	Message         string
	StatusCode      int
	SeverityText    string
	Resource        map[string]interface{}
	Latency         time.Duration
	ClusterID string
}
type JSONFormatter struct {
	logrus.Formatter
}

func (this *JSONFormatter)  Format(e *logrus.Entry) (logData []byte, err error) {
	var m = HarkLog{
		Timestamp:    e.Time,
		SeverityText: e.Level.String(),
		Message:      e.Message,
		Resource:     e.Data,
	}
	if e.Context != nil{
		c, ok := e.Context.(*gin.Context)
		if ok{
			startTime, exists := c.Get("startTime")
			if !exists{
				m.Latency = m.Timestamp.Sub(startTime.(time.Time))
			}
			clusterID := c.Param("clusterID")
			if clusterID != "" {
				m.ClusterID = clusterID
			}
			m.User = c.GetString("user")
			m.AccessTokenHash = c.GetString("accessTokenHash")
			m.Attributes = c.Keys
			m.Attributes["headers"] = c.Request.Header
			m.Name= c.Request.URL.Path
			m.RawQuery = c.Request.URL.RawQuery
			m.RequestIp = c.ClientIP()
			m.Method = c.Request.Method
			m.StatusCode = c.Writer.Status()
		}
	}
	logData, err = json.Marshal(m)
	logData = append(logData, byte(10))
	return
}


// Setup comment lint rebel
func Setup() {
	logrus.SetFormatter(new(JSONFormatter))
	logrus.SetLevel(logrus.InfoLevel)
}

